package com.example.hospital.mapper;

import com.example.hospital.domain.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    @Insert("INSERT INTO user (username, password, name, gender, age, phone, id_card, create_time, update_time) " +
            "VALUES (#{username}, #{password}, #{name}, #{gender}, #{age}, #{phone}, #{idCard}, NOW(), NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "userId")
    int insert(User user);

    @Select("SELECT * FROM user WHERE username = #{username}")
    User findByUsername(@Param("username") String username);

    @Select("SELECT * FROM user WHERE phone = #{phone}")
    User findByPhone(@Param("phone") String phone);

    @Select("SELECT * FROM user WHERE user_id = #{userId}")
    User findById(@Param("userId") Long userId);

    @Update("UPDATE user SET name=#{name}, gender=#{gender}, age=#{age}, phone=#{phone}, id_card=#{idCard}, update_time=NOW() WHERE user_id=#{userId}")
    int updateProfile(User user);

    @Update("UPDATE user SET password=#{password}, update_time=NOW() WHERE user_id=#{userId}")
    int updatePassword(@Param("userId") Long userId, @Param("password") String password);

    @Select({
            "<script>",
            "SELECT * FROM user",
            "<where>",
            "  <if test=\"name != null and name != ''\"> AND name LIKE CONCAT('%', #{name}, '%') </if>",
            "  <if test=\"phone != null and phone != ''\"> AND phone = #{phone} </if>",
            "  <if test=\"gender != null and gender != ''\"> AND gender = #{gender} </if>",
            "</where>",
            "ORDER BY create_time DESC",
            "LIMIT #{limit} OFFSET #{offset}",
            "</script>"
    })
    List<User> list(@Param("name") String name,
                    @Param("phone") String phone,
                    @Param("gender") String gender,
                    @Param("limit") int limit,
                    @Param("offset") int offset);

    @Select({
            "<script>",
            "SELECT COUNT(1) FROM user",
            "<where>",
            "  <if test=\"name != null and name != ''\"> AND name LIKE CONCAT('%', #{name}, '%') </if>",
            "  <if test=\"phone != null and phone != ''\"> AND phone = #{phone} </if>",
            "  <if test=\"gender != null and gender != ''\"> AND gender = #{gender} </if>",
            "</where>",
            "</script>"
    })
    long count(@Param("name") String name,
               @Param("phone") String phone,
               @Param("gender") String gender);
}